package com.haima.sage.bigdata.api.common;

import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class SignUtils {

    public static String makeGetRaw(String secret, String requestURI, Map<String, ?> params,
                                    String appKey, String userId, String userName, Long timestamp) {
        List<String> keys = new ArrayList<>();
        if (params != null) {
            keys.addAll(params.keySet());
            Collections.sort(keys);
        }
        StringBuilder buf = new StringBuilder();
        buf.append(secret);
        buf.append(requestURI).append("?");
        buf.append("appkey=").append(appKey);
        buf.append("&appUserId=").append(userId);
        buf.append("&appUserName=").append(userName);
        buf.append("&timestamp=").append(timestamp);

        if (params != null) {
            for (String key : keys) {
                buf.append("&").append(key).append("=");
                Object value = params.get(key);
                if (value != null) {
                    buf.append(value.toString());
                }
            }
        }
        return buf.toString();
    }

    /**
     * GET 方式的签名算法
     *
     * @param secret
     * @param requestURI
     * @param params
     * @param appKey
     * @param userId
     * @param userName
     * @param timestamp
     * @return
     */
    public static String digest(String secret, String requestURI, Map<String, ?> params,
                                String appKey, String userId, String userName, Long timestamp) {
        String uri = makeGetRaw(secret, requestURI, params, appKey, userId, userName, timestamp);
        return digest(uri);
    }

    /**
     * 签名算法
     *
     * @param raw
     * @return
     */
    public static String digest(String raw) {
        return DigestUtils.md5DigestAsHex(raw.getBytes());
    }


    /**
     * 非GET方式的签名算法
     *
     * @param secret
     * @param requestURI
     * @param body
     * @return
     */
    public static String digest(String secret, String requestURI, String body) {
        String raw = makeNotGetRaw(secret, requestURI, body);
        return digest(raw);
    }

    public static String makeNotGetRaw(String secret, String requestURI, String body) {
        StringBuilder buf = new StringBuilder();
        buf.append(secret);
        buf.append(requestURI).append("?");
        buf.append("body=").append(body);
        return buf.toString();
    }

}
